package com.ss.filter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mysql.cj.log.Log;
import com.ss.dto.LoginUserDto;
import com.ss.redis.RedisCache;
import com.ss.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Objects;

@Slf4j
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private RedisCache redisCache;

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        String token = httpServletRequest.getHeader("token");
        if (!StringUtils.hasText(token)) {
            filterChain.doFilter(httpServletRequest, httpServletResponse);
            return;
        }
        String userId = null;
        try {
            //解析token
            Claims claims = JwtUtils.parserJWT(token);
            userId = claims.getSubject();
        } catch (Exception e) {
            log.error("JwtAuthenticationTokenFilter", e);
            throw new RuntimeException(e);
        }
        //在redis获取登录用户的信息
        String redisKey = "login:" + userId;

        //TODO 为什么不能直接转换成LoginUserDto对象
        JSONObject loginUserDtoJson = redisCache.getCacheObject(redisKey);
        if (Objects.isNull(loginUserDtoJson)) {
            throw new RuntimeException("用户未登录");
        }
        LoginUserDto loginUserDto = JSON.parseObject(JSON.toJSONString(loginUserDtoJson), LoginUserDto.class);

//        LoginUserDto loginUserDto = redisCache.getCacheObject(redisKey);
//        if (Objects.isNull(loginUserDto)) {
//            throw new RuntimeException("用户未登录");
//        }
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(loginUserDto,
                null, loginUserDto.getAuthorities());//第三个参数是权限
        SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
        filterChain.doFilter(httpServletRequest, httpServletResponse);
    }
}
